import React, { useState } from 'react';
import OutlinedInput from '@material-ui/core/OutlinedInput';
import InputLabel from '@material-ui/core/InputLabel';
import FormHelperText from '@material-ui/core/FormHelperText';
import FormControl from '@material-ui/core/FormControl';
import InputAdornment from '@material-ui/core/InputAdornment';
import 'date-fns';
import SearchIcon from '@material-ui/icons/Search';
import IconButton from '@material-ui/core/IconButton';
import zhLocale from "date-fns/locale/zh-CN";
import DateFnsUtils from '@date-io/date-fns';
import { KeyboardDatePicker, KeyboardDateTimePicker, KeyboardTimePicker, MuiPickersUtilsProvider } from '@material-ui/pickers';
import { loc, loc_lang, ck_date_range, ck_date, obj_date, obj_str, ErrView, Dlg, loc_day, loc_year, loc_time, loc_dt } from 'sui';

const get_loc = () => {
    if (loc_lang() === "zhcn") {
        return zhLocale;
    }

    return null;
};

const IkRangeDate = ({ name_s, name_e, form, value, disabled=false, format="yyyy-MM-dd", views=['year', 'month', 'day'] }) => {
    return (
        <MuiPickersUtilsProvider utils={DateFnsUtils} locale={get_loc()}>
            <div className="mr-6">
                <KeyboardDatePicker
                    format={format}
                    views={views}
                    disabled={disabled}
                    label={loc("l_529")}
                    error={Boolean(form.err[name_s])}
                    helperText={obj_str(form.err, name_s)}
                    value={obj_date(value, name_s)}
                    ampm={false}
                    inputVariant="outlined"
                    margin="normal"
                    id="date-start"
                    name="date-start"
                    cancelLabel={loc("l_546")}
                    okLabel={loc("l_541")}
                    clearable={false}
                    onChange={v => form.hcmd(name_s, v)}/>
            </div>
            <div className="mr-6">
                <KeyboardDatePicker
                    format={format}
                    views={views}
                    disabled={disabled}
                    label={loc("l_528")}
                    error={Boolean(form.err[name_e])}
                    helperText={obj_str(form.err, name_e)}
                    value={obj_date(value, name_e)}
                    ampm={false}
                    inputVariant="outlined"
                    margin="normal"
                    id="date-end"
                    name="date-end"
                    cancelLabel={loc("l_546")}
                    okLabel={loc("l_541")}
                    clearable={false}
                    onChange={v => form.hcmd(name_e, v)}/>
            </div>
        </MuiPickersUtilsProvider>
    );
};

const IkRangeTime = ({ name_s, name_e, form, value, disabled=false }) => {
    return (
        <MuiPickersUtilsProvider utils={DateFnsUtils} locale={get_loc()}>
            <div className="mr-6">
                <KeyboardTimePicker
                    disabled={disabled}
                    label={loc("l_529")}
                    error={Boolean(form.err[name_s])}
                    helperText={obj_str(form.err, name_s)}
                    value={obj_date(value, name_s)}
                    ampm={false}
                    inputVariant="outlined"
                    margin="normal"
                    id="time-start"
                    name="time-start"
                    cancelLabel={loc("l_546")}
                    okLabel={loc("l_541")}
                    clearable={false}
                    onChange={v => form.hcmd(name_s, v)}/>
            </div>
            <div className="mr-6">
                <KeyboardTimePicker
                    disabled={disabled}
                    label={loc("l_528")}
                    error={Boolean(form.err[name_e])}
                    helperText={obj_str(form.err, name_e)}
                    value={obj_date(value, name_e)}
                    ampm={false}
                    inputVariant="outlined"
                    margin="normal"
                    id="time-end"
                    name="time-end"
                    cancelLabel={loc("l_546")}
                    okLabel={loc("l_541")}
                    clearable={false}
                    onChange={v => form.hcmd(name_e, v)}/>
            </div>
        </MuiPickersUtilsProvider>
    );
};

const IkDatetime = ({ name_s, name_e, form, value, disabled=false, mg="normal", format="yyyy-MM-dd HH:mm" }) => {
    return (
        <MuiPickersUtilsProvider utils={DateFnsUtils} locale={get_loc()}>
            <div className="mr-6">
                <KeyboardDateTimePicker
                    disabled={disabled}
                    label={loc("l_529")}
                    error={Boolean(form.err[name_s])}
                    helperText={obj_str(form.err, name_s)}
                    value={obj_date(value, name_s)}
                    ampm={false}
                    inputVariant="outlined"
                    margin={mg}
                    id="date-start"
                    name="date-start"
                    cancelLabel={loc("l_546")}
                    okLabel={loc("l_541")}
                    clearable={false}
                    format={format}
                    onChange={v => form.hcmd(name_s, v)}/>
            </div>
            <div className="mr-6">
                <KeyboardDateTimePicker
                    disabled={disabled}
                    label={loc("l_528")}
                    error={Boolean(form.err[name_e])}
                    helperText={obj_str(form.err, name_e)}
                    value={obj_date(value, name_e)}
                    ampm={false}
                    inputVariant="outlined"
                    margin="normal"
                    id="date-end"
                    name="date-end"
                    cancelLabel={loc("l_546")}
                    okLabel={loc("l_541")}
                    clearable={false}
                    format={format}
                    onChange={v => form.hcmd(name_e, v)}/>
            </div>
        </MuiPickersUtilsProvider>
    );
};

const find_date_format = (s, e, type="date") => {
    if (type === "time") {
        return `${loc_time(s)} ${loc("l_590")} ${loc_time(e)}`;
    }

    if (type === "date") {
        return `${loc_day(s)} ${loc("l_590")} ${loc_day(e)}`;
    }

    if (type === "year") {
        return `${loc_year(s)} ${loc("l_590")} ${loc_year(e)}`;
    }

    return `${loc_dt(s)} ${loc("l_590")} ${loc_dt(e)}`;
};

const IkFindDate = ({ label, className, form, value, name, name_s, name_e, width=410, mg="normal", type="datetime" }) => {
    const [open, setOpen] = useState(false);
    const [err, setErr] = useState("");

    const hdone = () => {
        const start = value[name_s];
        const end = value[name_e];

        const s = ck_date(start);
        if (s) {
            setErr(s);
            return;
        }

        const e = ck_date_range(start, end);
        if (e) {
            setErr(e);
            return;
        }

        setOpen(false);

        form.hcmd(name_s, value[name_s]);
        form.hcmd(name_e, value[name_e]);
        form.hcmd(name, find_date_format(value[name_s], value[name_e], type));
    };

    const getInfo = () => {
        const info = obj_str(form.err, name);
        if (info) {
            return <FormHelperText>{info}</FormHelperText>;
        }

        return null;
    };

    const View = () => {
        if (!open) {
            return null;
        }

        if (type === "time") {
            return <IkRangeTime name_s={name_s} name_e={name_e} form={form} value={value}/>;
        }

        if (type === "date") {
            return <IkRangeDate name_s={name_s} name_e={name_e} form={form} value={value}/>;
        }

        if (type === "year") {
            return <IkRangeDate name_s={name_s} name_e={name_e} form={form} value={value} format="yyyy" views={['year']}/>;
        }

        return <IkDatetime name_s={name_s} name_e={name_e} form={form} value={value}/>;
    };

    const sz = mg === "dense" ? "small" : "medium";

    return (
        <div className={className}>
            <FormControl margin={mg} variant="outlined" style={{ width: width + "px" }} error={Boolean(form.err[name])}>
                <InputLabel>{label}</InputLabel>
                <OutlinedInput
                    disabled={true}
                    name={name}
                    type="text"
                    value={obj_str(value, name)}
                    endAdornment={
                        <InputAdornment position="end">
                            <IconButton size={sz} onClick={() => setOpen(true)} name={`btn${name}`}>
                                <SearchIcon fontSize={sz}/>
                            </IconButton>
                        </InputAdornment>
                    }
                    label={label}
                />
                {getInfo()}
            </FormControl>
            <Dlg open={open} hcancel={() => setOpen(false)} title={label} hcmd={hdone} name={`bt${name}`}>
                <View/>
                <ErrView err={err}/>
            </Dlg>
        </div>
    );
};

const IkDate = ({ name, form, value, disabled=false, format="yyyy-MM-dd", label, mg="normal" }) => {
    return (
        <MuiPickersUtilsProvider utils={DateFnsUtils} locale={get_loc()}>
            <div className="mr-6">
                <KeyboardDatePicker
                    format={format}
                    disabled={disabled}
                    label={label}
                    error={Boolean(form.err[name])}
                    helperText={obj_str(form.err, name)}
                    value={obj_date(value, name)}
                    ampm={false}
                    inputVariant="outlined"
                    margin={mg}
                    id="date-start"
                    name="date-start"
                    cancelLabel={loc("l_546")}
                    okLabel={loc("l_541")}
                    clearable={false}
                    onChange={v => form.hcmd(name, v)}/>
            </div>
        </MuiPickersUtilsProvider>
    );
};

const IkYm = ({ name, form, value, disabled=false, format="yyyy-MM", label, mg="normal" }) => {
    return (
        <MuiPickersUtilsProvider utils={DateFnsUtils} locale={get_loc()}>
            <div className="mr-6">
                <KeyboardDatePicker
                    format={format}
                    disabled={disabled}
                    views={['year', 'month']}
                    label={label}
                    error={Boolean(form.err[name])}
                    helperText={obj_str(form.err, name)}
                    value={obj_date(value, name)}
                    ampm={false}
                    inputVariant="outlined"
                    margin={mg}
                    id="date-start"
                    name="date-start"
                    cancelLabel={loc("l_546")}
                    okLabel={loc("l_541")}
                    clearable={false}
                    onChange={v => form.hcmd(name, v)}/>
            </div>
        </MuiPickersUtilsProvider>
    );
};

const IkY = ({ name, form, value, disabled=false, format="yyyy", label, mg="normal" }) => {
    return (
        <MuiPickersUtilsProvider utils={DateFnsUtils} locale={get_loc()}>
            <div className="mr-6">
                <KeyboardDatePicker
                    format={format}
                    disabled={disabled}
                    views={['year']}
                    label={label}
                    error={Boolean(form.err[name])}
                    helperText={obj_str(form.err, name)}
                    value={obj_date(value, name)}
                    ampm={false}
                    inputVariant="outlined"
                    margin={mg}
                    id="date-start"
                    name="date-start"
                    cancelLabel={loc("l_546")}
                    okLabel={loc("l_541")}
                    clearable={false}
                    onChange={v => form.hcmd(name, v)}/>
            </div>
        </MuiPickersUtilsProvider>
    );
};

const IkTime = ({ name, form, value, disabled=false }) => {
    return (
        <MuiPickersUtilsProvider utils={DateFnsUtils} locale={get_loc()}>
            <div className="mr-6">
                <KeyboardTimePicker
                    disabled={disabled}
                    label={loc("l_529")}
                    error={Boolean(form.err[name])}
                    helperText={obj_str(form.err, name)}
                    value={obj_date(value, name)}
                    ampm={false}
                    inputVariant="outlined"
                    margin="normal"
                    id={name}
                    name={name}
                    cancelLabel={loc("l_546")}
                    okLabel={loc("l_541")}
                    clearable={false}
                    onChange={v => form.hcmd(name, v)}/>
            </div>
        </MuiPickersUtilsProvider>
    );
};

const IkDT = ({ name, form, value, disabled=false, format="yyyy-MM-dd HH:mm", label, mg="normal" }) => {
    return (
        <MuiPickersUtilsProvider utils={DateFnsUtils} locale={get_loc()}>
            <div className="mr-6">
                <KeyboardDateTimePicker
                    format={format}
                    disabled={disabled}
                    label={label}
                    error={Boolean(form.err[name])}
                    helperText={obj_str(form.err, name)}
                    value={obj_date(value, name)}
                    ampm={false}
                    inputVariant="outlined"
                    margin={mg}
                    id="date-start"
                    name="date-start"
                    cancelLabel={loc("l_546")}
                    okLabel={loc("l_541")}
                    clearable={false}
                    onChange={v => form.hcmd(name, v)}/>
            </div>
        </MuiPickersUtilsProvider>
    );
};

export {IkDT, IkY, IkTime, IkYm, IkDate, IkRangeTime, find_date_format, IkFindDate, IkDatetime};
